/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-02-27 18:32:39
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-02-27 20:45:28
 * @FilePath: \web-warningdevicemanage-v2\src\utils\bigdownload.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { pageStore } from '@/stores/modules/page';
import { message } from 'ant-design-vue';
import {
  reqDownloadFileByPath,
  reqFileByFileId,
  reqFileDownloadRateByFileId,
} from '@/api/device';

const PageStore = pageStore();
// 大文件下载
let fileId = '' as any; // 文件的id
// 1获取文件fileId
const getDownloadFileByPath = async (data: any) => {
  fileId = '' as any;
  const res = await reqDownloadFileByPath(data);
  if (res.code === 200) {
    console.log('res获取文件fileId', res);
    fileId = res.data || '';
    console.log('fileId', fileId);
    if (fileId) {
      LoopGetProgress(fileId);
    }
  }
};

let schedule = '0' as any; // 下载进度
let Timer: any;
const LoopGetProgress = (fileId: any) => {
  schedule = '0' as any;
  Timer = setInterval(async () => {
    PageStore.setProgressNum(schedule);
    if (schedule === '100.0') {
      clearInterval(Timer);
      await getFileByFileId({
        fileId: fileId,
      });
    } else {
      const res = await reqFileDownloadRateByFileId({
        fileId: fileId,
      });
      if (res.code === 200) {
        schedule = res.data;
      } else {
        clearInterval(Timer);
        message.error('下载失败');
        setTimeout(() => {
          PageStore.setOpenProgress(false);
          PageStore.setProgressNum('0');
        }, 1000);
      }
    }
  }, 3000);
};

const getFileByFileId = async (data: any) => {
  message.destroy();
  message.success('下载成功');
  setTimeout(() => {
    PageStore.setOpenProgress(false);
    PageStore.setProgressNum('0');
  }, 1000);
  const res = await reqFileByFileId(data);
};

// 参数
interface TDownload {
  code: string;
  url: string;
}
export const Bigdownload = async (obj: TDownload) => {
  PageStore.setProgressNum('0');
  PageStore.setOpenProgress(true);
  await getDownloadFileByPath(obj);
};
